package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/cart")
public class CartApiController {

    @Resource
    private CartInfoService cartInfoService;

    //添加商品到购物车
    @PostMapping("/addToCart/{skuId}/{skuNum}")
    public Result addToCart(@PathVariable Long skuId,
                            @PathVariable Integer skuNum){
        cartInfoService.addToCart(skuId,skuNum);
        return Result.ok();
    }

    //查询购物车商品
    @GetMapping("/getCartInfo/{skuId}")
    public Result getCartInfo(@PathVariable Long skuId){
        CartInfo cartInfo = cartInfoService.getCartInfo(skuId);
        return Result.ok(cartInfo);
    }

    //查询购物车所有商品
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request){
        //获取真实用户ID
        String userId = AuthContextHolder.getUserId(request);
        //获取临时用户ID
        String userTempId = AuthContextHolder.getUserTempId(request);

        List<CartInfo> cartInfoList = cartInfoService.cartList(userId,userTempId);
        return Result.ok(cartInfoList);
    }

    // 更新选中状态
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId,
                            @PathVariable Integer isChecked){

        cartInfoService.checkCart(skuId,isChecked);
        return Result.ok();
    }

    //删除购物车
    @DeleteMapping("/deleteCart/{skuId}")
    public Result deleteCart(@PathVariable Long skuId){
        cartInfoService.deleteCart(skuId);
        return Result.ok();
    }

    //查询选中的购物车集合
    @GetMapping("/cartListIsChecked")
    public List<CartInfo> cartListIsChecked(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        List<CartInfo> cartListIsChecked = cartInfoService.cartListIsChecked(userId);
        return cartListIsChecked;
    }
}
